package com.dupf.product.web.controller.product;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.dupf.common.base.BaseController;
import com.dupf.common.util.ItvJsonUtil;
import com.dupf.common.validator.LengthValidator;
import com.dupf.product.common.constant.ProductResult;
import com.dupf.product.common.constant.ProductResultConstant;
import com.dupf.product.dao.model.ProductVariant;
import com.dupf.product.dao.model.ProductVariantExample;
import com.dupf.product.rpc.api.ProductVariantService;
import com.dupf.upms.rpc.api.UpmsApiService;
import com.google.common.base.Splitter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品controller
 * Created by dupf on 2018/3/20.
 */
@Controller
@Api(value = "变体库设置", description = "变体库设置")
@RequestMapping("/variant")
public class ProductVariantController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductVariantController.class);

    @Autowired
    private ProductVariantService variantService;

    @Autowired
    private UpmsApiService upmsApiService;

    @ApiOperation(value = "变体列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(
            @RequestParam(value = "type") Integer type,
            @RequestParam(required = false, value = "variantZh") String variantZh,
            @RequestParam(required = false, value = "userIds") String userIds,
            @RequestParam(required = false, defaultValue = "false", value = "orders") Boolean orders,
            @RequestParam(required = false, defaultValue = "1", value = "currentPage") int currentPage,
            @RequestParam(required = false, defaultValue = "20", value = "limit") int pageSize,
            HttpServletRequest request
    ) {

        Integer orgId = (Integer) request.getAttribute("currentOrgId");
        Integer currentUserId = (Integer) request.getAttribute("currentUserId");

        ProductVariantExample example = new ProductVariantExample();
        ProductVariantExample.Criteria criteria = example.createCriteria();
        criteria.andOrgIdEqualTo(orgId);
        criteria.andTypeEqualTo(type);

        if (StringUtils.isNotEmpty(variantZh)) {
            criteria.andVariantZhLike(variantZh + "%");
        }

        if (StringUtils.isNotEmpty(userIds)) {
            criteria.andUserIdIn(Splitter.on(",").splitToList(userIds).stream().map(Integer::valueOf).collect(Collectors.toList()));
        } else {
            criteria.andUserIdEqualTo(currentUserId);
        }

        if (orders) {
            example.setOrderByClause("ctime DESC, orders ASC");
        }

        List<ProductVariant> rows = variantService.selectByExampleForOffsetPage(example, (currentPage - 1) * pageSize, pageSize);

//        Map<Integer, String> userMap = new HashMap<>();
//        Set<Integer> variantUserIds = rows.stream().map(ProductVariant::getUserId).collect(Collectors.toSet());
//        if (!CollectionUtils.isEmpty(variantUserIds)) {
//            List<UpmsUser> userList = upmsApiService.getUserListByUserIds(variantUserIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
//            if (!CollectionUtils.isEmpty(userList)) {
//                userMap = userList.stream().collect(Collectors.toMap(UpmsUser::getUserId, UpmsUser::getRealname, (k1, k2) -> k1));
//            }
//        }
//
//        Subject subject = SecurityUtils.getSubject();
//        String username = (String) subject.getPrincipal();
//        List<UpmsUser> operableUserList = upmsApiService.getOperableUserListByCache(username, orgId);
//        Set<Integer> operableUserIds = operableUserList.stream().map(UpmsUser::getUserId).collect(Collectors.toSet());
//        operableUserIds.add(currentUserId);
//
//        JSONArray resultRows = new JSONArray();
//        for (ProductVariant p : rows) {
//            JSONObject data = JSONObject.fromObject(p);
//            data.put("username", userMap.getOrDefault(p.getUserId(), "XXXXX"));
//            data.put("editable", operableUserIds.contains(p.getUserId()));
//            resultRows.add(data);
//        }
//
//        List<Map<String,Object>> userCountList = variantService.getUserVariantCountList(orgId);
//        Map<Integer, String> variantUserMap = new HashMap<>();
//        List<Integer> variantuserIds =  userCountList.stream().map(p->(Integer)p.get("userId")).collect(Collectors.toList());
//        if(!CollectionUtils.isEmpty(variantuserIds)){
//            List<UpmsUser> userList = upmsApiService.getUserListByUserIds(variantuserIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
//            if (!CollectionUtils.isEmpty(userList)) {
//                variantUserMap = userList.stream().collect(Collectors.toMap(UpmsUser::getUserId, UpmsUser::getRealname, (k1, k2) -> k1));
//            }
//        }
//
//        List<Map<String,Object>> userCountListResult = new ArrayList<>();
////        userCountList.forEach(p->{
//        for (Map<String,Object> p : userCountList) {
//            Map<String,Object> map = new HashMap<>();
//            map.put("text", variantUserMap.getOrDefault(p.get("userId"), "--") +"  "+p.getOrDefault("count", 0));
//            map.put("value", String.valueOf(p.get("userId")));
//            userCountListResult.add(map);
//        };

        int total = variantService.countByExample(example);
        Map<String, Object> result = new HashMap<>();
        result.put("list", rows);
//        result.put("userList", userCountListResult);
        JSONObject pagination = new JSONObject();
        pagination.put("total", total);
        pagination.put("pageSize", pageSize);
        pagination.put("pageSize", pageSize);
        pagination.put("currentPage", currentPage);
        result.put("pagination", pagination);

        return new ProductResult(ProductResultConstant.SUCCESS, result);
    }

    @ApiOperation(value = "添加变体")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(HttpServletRequest request) throws IOException {
        Integer orgId = (Integer) request.getAttribute("currentOrgId");
        Integer userId = (Integer) request.getAttribute("currentUserId");

        String requestStr = super.getInputStream(request);
        ProductVariant productVariant = ItvJsonUtil.readValue(requestStr, ProductVariant.class);

        if (productVariant == null || StringUtils.isEmpty(productVariant.getVariantZh())) {
            return new ProductResult(ProductResultConstant.INVALID_PARAMETER, "没有中文变体");
        }

        ComplexResult result = FluentValidator.checkAll()
                .on(productVariant.getVariantZh(), new LengthValidator(1, 20, "中文变体"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ProductResult(ProductResultConstant.INVALID_PARAMETER, result.getErrors());
        }

        ProductVariantExample example = new ProductVariantExample();
        example.createCriteria().andVariantZhEqualTo(productVariant.getVariantZh());

        long count = variantService.countByExample(example);
        if (count > 0) {
            return new ProductResult(ProductResultConstant.EXISTED, "该变体已存在");
        }

        productVariant.setOrders(variantService.getOrder(productVariant));
        // 暂定全部是平台默认的
        productVariant.setOrgId(orgId);
        productVariant.setUserId(userId);
        productVariant.setCtime(System.currentTimeMillis());

        variantService.addVariant(productVariant);

        return new ProductResult(ProductResultConstant.SUCCESS, productVariant.getId());
    }

    @ApiOperation(value = "删除变体")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids, HttpServletRequest request) throws IOException {

        int count = variantService.deleteByPrimaryKeys(ids);
        return new ProductResult(ProductResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改变体")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(HttpServletRequest request) throws IOException {

        Integer orgId = (Integer) request.getAttribute("currentOrgId");

        String requestStr = super.getInputStream(request);
        ProductVariant productVariant = ItvJsonUtil.readValue(requestStr, ProductVariant.class);

        if (productVariant == null || StringUtils.isEmpty(productVariant.getVariantZh())) {
            return new ProductResult(ProductResultConstant.INVALID_PARAMETER, "没有中文变体");
        }

        ComplexResult result = FluentValidator.checkAll()
                .on(productVariant.getVariantZh(), new LengthValidator(1, 20, "中文变体"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ProductResult(ProductResultConstant.INVALID_PARAMETER, result.getErrors());
        }

        ProductVariantExample example = new ProductVariantExample();
        example.createCriteria().andUserIdEqualTo(productVariant.getUserId()).andVariantZhEqualTo(productVariant.getVariantZh()).andIdNotEqualTo(productVariant.getId());

        int count = variantService.countByExample(example);
        if (count > 0) {
            return new ProductResult(ProductResultConstant.EXISTED, "该变体已存在");
        }

        productVariant.setOrders(variantService.getOrder(productVariant));
        productVariant.setOrgId(orgId);
        productVariant.setMtime(System.currentTimeMillis());

        variantService.updateByPrimaryKeySelective(productVariant);

        return new ProductResult(ProductResultConstant.SUCCESS, productVariant.getId());
    }
}